package com.wulinbus.controller.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fancy.common.security.MD5;
import com.fancy.common.utils.DateUtil;
import com.wulinbus.model.UserModel;
import com.wulinbus.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminAuthController {

	@Resource
	private UserService userService;
	
	@RequestMapping("login.html")
	public String login() {
		return "admin/login";
	}
	
	/**
	 * 用户登陆
	 */
	@RequestMapping(value = "login.json", method = { RequestMethod.POST })
	public void login_post(String email, String pwd, HttpServletResponse response) throws IOException {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("email", email);
		param.put("pwd", MD5.md5(pwd));
		UserModel userModel = userService.adminLogin(param);
		if (userModel == null) 
		{
			response.getWriter().write("{\"success\":\"false\",\"msg\":\"用户名或者密码错误！\"}");
		}                              
		else                                
		{
			Integer uid = userModel.getUid();
			String login_time=DateUtil.getCurDateYmd();
			userService.addLoginTime(uid,login_time);
			Cookie cookie = new Cookie("muid", uid.toString());
			cookie.setPath("/");
			response.addCookie(cookie);
			response.getWriter().write("{\"success\":\"true\",\"msg\":\"登录成功!\"}");
		}
	}

	
	@RequestMapping("logout.html")
	public String logout(HttpServletResponse response) {
		Cookie cookie = new Cookie("muid", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		return "admin/login";
	}
}
